<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>日志查询系统</title>
       <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
    <style>
        .pagination-info {
            font-size: 0.9rem;
            color: #6c757d;
        }
        .status-badge {
            min-width: 60px;
            text-align: center;
        }
        .search-form {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <h2 class="mb-4">日志查询系统</h2>
        
        <!-- 统计信息显示 -->
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div>
                <h5 id="totalCount" class="mb-0"></h5>
            </div>
            <div class="pagination-info" id="paginationInfo"></div>
        </div>
        
        <!-- 搜索表单 -->
        <div class="search-form mb-4">
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="input-group">
                        <span class="input-group-text">时间范围</span>
                        <input type="datetime-local" class="form-control" id="startTime">
                        <input type="datetime-local" class="form-control" id="endTime">
                    </div>
                </div>
                <div class="col-md-1">
                    <select class="form-select" id="statusFilter">
                        <option value="">全部</option>
                        <option value="1">成功</option>
                        <option value="0">失败</option>
                    </select>
                </div>

                    <div class="col-md-2">
                    <select class="form-select" id="proType">
                        <option value="">全部</option>
                          {% for info in pro_list %}
                            <option value="{{info.type}}">{{info.title}}</option>
                          {% endfor %}

                    </select>
                </div>
                <div class="col-md-3">
                    <button class="btn btn-primary me-2" id="searchBtn">
                        <i class="bi bi-search me-1"></i>搜索
                    </button>
                    <button class="btn btn-outline-secondary" id="resetBtn">
                        <i class="bi bi-arrow-repeat me-1"></i>重置
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>类型</th>
                        <th>状态</th>
                        <th>返回值</th>
                        <th>时间</th>
                    </tr>
                </thead>
                <tbody id="dataBody">
                    <!-- 动态数据将在这里渲染 -->
                </tbody>
            </table>
        </div>
        
        <!-- 分页导航 -->
        <nav aria-label="Page navigation">
            <ul class="pagination justify-content-center mb-3" id="pagination"></ul>
        </nav>
        
        <!-- 每页显示数量 -->
        <div class="d-flex justify-content-center align-items-center">
            <span class="me-2">每页显示：</span>
            <div class="input-group w-auto">
                <select class="form-select" id="perPageSelect">
                    <option value="5">5</option>
                    <option value="10" selected>10</option>
                    <option value="20">20</option>
                    <option value="50">50</option>
                </select>
                <span class="input-group-text" id="currentPerPageDisplay">10</span>
            </div>
        </div>
    </div>

    <script>
        // 全局配置
        let currentPage = 1;
        let perPage = 10;
        let searchParams = {};
        
        // DOM加载完成后执行
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化显示当前每页条数
            document.getElementById('currentPerPageDisplay').textContent = perPage;
            
            // 初始化页面
            loadData();
            
            // 搜索按钮点击
            document.getElementById('searchBtn').addEventListener('click', () => {
                searchParams = {
                    startTime: document.getElementById('startTime').value,
                    endTime: document.getElementById('endTime').value,
                    status: document.getElementById('statusFilter').value,
                    proType:document.getElementById('proType').value
                };
                currentPage = 1;
                loadData();
            });
            
            // 重置按钮点击
            document.getElementById('resetBtn').addEventListener('click', () => {
                document.getElementById('startTime').value = '';
                document.getElementById('endTime').value = '';
                document.getElementById('statusFilter').value = '';
                document.getElementById('proType').value= '';
                searchParams = {};
                currentPage = 1;
                loadData();
            });
            
            // 每页显示数量变化
            document.getElementById('perPageSelect').addEventListener('change', function() {
                perPage = parseInt(this.value);
                document.getElementById('currentPerPageDisplay').textContent = perPage;
                currentPage = 1;
                loadData();
            });
        });
        
        // AJAX加载数据
        function loadData() {
            const url = `/api/logs?page=${currentPage}&per_page=${perPage}`;
            const params = new URLSearchParams(searchParams);
            
            // 显示加载状态
            document.getElementById('dataBody').innerHTML = `
                <tr>
                    <td colspan="6" class="text-center py-4">
                        <div class="spinner-border text-primary" role="status"></div>
                        <div class="mt-2">加载中...</div>
                    </td>
                </tr>
            `;
            
            fetch(`${url}&${params}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 更新统计信息
                    document.getElementById('totalCount').textContent = 
                        `共 ${data.total} 条记录`;
                    
                    const totalPages = Math.ceil(data.total / perPage);
                    document.getElementById('paginationInfo').textContent = 
                        `第 ${currentPage} 页 / 共 ${totalPages} 页`;
                    
                    // 渲染数据
                    renderData(data);
                    
                    // 渲染分页
                    renderPagination(data.total, currentPage, perPage);
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('dataBody').innerHTML = `
                        <tr>
                            <td colspan="6" class="text-center py-4">
                                <div class="alert alert-danger">
                                    数据加载失败: ${error.message}
                                </div>
                            </td>
                        </tr>
                    `;
                });
        }
        
        // 渲染数据到表格
        function renderData(data) {
            const tbody = document.getElementById('dataBody');
            tbody.innerHTML = '';
            
            if (data.data.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <div class="alert alert-info">没有找到匹配的记录</div>
                        </td>
                    </tr>
                `;
                return;
            }
            
            data.data.forEach(item => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${item.id}</td>
                    <td>${item.title}</td>
                    <td>${item.type}</td>
                    <td>
                        <span class="badge ${item.result_res ? 'bg-success' : 'bg-danger'} status-badge">
                            ${item.result_res ? '成功' : '失败'}
                        </span>
                    </td>
                    <td class="text-break" style="max-width: 300px">${item.result_msg}</td>
                    <td>${new Date(item.add_time).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}</td>
                `;
                tbody.appendChild(row);
            });
        }
        
        // 渲染分页导航
        function renderPagination(total, current, perPage) {
            const totalPages = Math.ceil(total / perPage);
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';
            
            // 上一页按钮
            pagination.appendChild(
                createPageItem('<<', current > 1, current - 1)
            );
            
            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                if (i === 1 || i === totalPages || 
                    (i >= current - 2 && i <= current + 2)) {
                    pagination.appendChild(
                        createPageItem(i, i !== current, i)
                    );
                } else if (i === 3 && current > 5) {
                    pagination.appendChild(createPageItem('...', false));
                } else if (i === totalPages - 2 && current < totalPages - 4) {
                    pagination.appendChild(createPageItem('...', false));
                }
            }
            
            // 下一页按钮
            pagination.appendChild(
                createPageItem('>>', current < totalPages, current + 1)
            );
        }
        
        // 创建分页项
        function createPageItem(text, enabled, pageNum) {
            const li = document.createElement('li');
            li.className = 'page-item';
            if (text === '...') {
                li.className += ' disabled';
            }
            
            const a = document.createElement('a');
            a.className = 'page-link';
            a.href = '#';
            a.textContent = text;
            
            if (enabled) {
                a.addEventListener('click', (e) => {
                    e.preventDefault();
                    currentPage = pageNum;
                    loadData();
                });
            } else {
                a.style.pointerEvents = 'none';
            }
            
            li.appendChild(a);
            return li;
        }
    </script>
</body>
</html>